package com.ias.agdis_r.manager;

import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.LoginActivity;
import com.ias.agdis_r.bean.message.SendMsgBean;
import com.ias.agdis_r.bean.other.ProgressBean;
import com.ias.agdis_r.impl.security.SecurityResponseImpl;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.module.RestfulUri;
import com.ias.agdis_r.netservice.BaseService;
import com.ias.agdis_r.netservice.SendMsgThread;
import com.ias.agdis_r.netservice.actions.WifiNetService;
import com.ias.agdis_r.netservice.listener.MessageSendSuccessListener;
import com.ias.agdis_r.service.GpsService;
import com.ias.agdis_r.util.MyMessage;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.ServiceLabelUtil;
import com.ias.agdis_r.util.ShowToast;
import com.ias.agdis_r.util.network.NetUtils;
import com.ias.agdis_r.util.sdcard.WriteLog;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 服务管理类
 *
 * @author wanghu
 */
public class ServiceManage {

	private boolean _isLogon = false;
	private int currentNetIndex = -1;
	private Handler handler = new Handler();
	private String sNetIp = "";
	private static ServiceManage instance = null;// 单例的服务管理器
	private List<BaseService> serviceArray = new ArrayList<BaseService>();// 服务列表
	private Map<String, ProgressBean> waitProcess = new HashMap<String, ProgressBean>();// 可根据需要修改成消息队列
	private GpsService gpsService = null;// Gps服务
	private boolean sendMsgFlag = true; // 发送消息标识，如果发送了RELO消息后，停止发送消息
	private Context context = DataBaseManager.getInstance().getContext();
	private Runnable waitRecvice = new Runnable() {
		@Override
		public void run() {
			clearWaitDialog(null);
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, context.getString(R.string.serviceTimeout), false);
		}
	};

    /**
     * 单例模式
     *
     * @return
     */
    public static ServiceManage getInstance() {
        if (instance == null) {
            instance = new ServiceManage();
        }
        return instance;
    }

    /**
     * 设置发送消息标记
     *
     * @param flag
     */
    public void setSendMsgFlag(boolean flag) {
        sendMsgFlag = flag;
    }

    public List<BaseService> getServiceArray() {
        return serviceArray;
    }

    public void closeAllService() {

        for (BaseService service : serviceArray) {
            service.close();
        }
    }

    /**
     * 启动登录页面
     */
    public void startLoginActivity() {
        try {
            if (!ServiceManage.getInstance().getIsLogon()) {
                //此处加标识，防止Activity启动过慢，连续启动Activity;
                ParameterModel.startLoginActivityFlag = true;
                Context context = DataBaseManager.getInstance().getContext();
                Intent intent = new Intent(context, LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 注销
     */
    public void onLogonOut() {

        NetUtils.MODIFY_NAME_FLAG = false;
        ServiceManage.getInstance().setLogon(false);
        JavaBeanManager.getInstance().deleteGpsData();
        JavaBeanManager.getInstance().deleteIQRYData();
        JavaBeanManager.getInstance().deleteUserLoginData();

        // 清除任务数据
        DataManager.getInstance().cleanReceiveList();
        DataManager.getInstance().cleanHistroyWorkList();
        DataManager.getInstance().cleanWorkList();
        DataManager.getInstance().cleanNFReceiveList();
        DataManager.getInstance().cleanNFHistroyWorkList();
        DataManager.getInstance().cleanNFWorkList();
        DataManager.getInstance().clearMessageList();

        // 注销发送IQRY信息
        ThreadManager.getInstance().stopIQYRThread();
        // 注销发送GPS信息
//        ThreadManager.getInstance().stopGPSThread();
        stopGPSService();
        // 停止行李单号上报线程
        ThreadManager.getInstance().stopSendLuggageBarCodeThread();
        // 注销锁定机位(目前没有在使用)
        // ThreadManager.getInstance().stopLockPsnThread();

        MessageManager.getInstance().setLastLogonOutMessage(null);
        // if (TaskReceiveView.getInstance() != null)
        // TaskReceiveView.getInstance().destroy();
        // 清除自动申请，航班订阅
        JavaBeanManager.getInstance().clearSUBFlightList();
        JavaBeanManager.getInstance().cleanQueryList();
        // 清除短语相关模板信息
        JavaBeanManager.getInstance().clearMSGTemplate();
        // 清除未完成任务TNB列表
        DataManager.getInstance().cleanUnfinishedTnbMap();
        //清除未完成通用任务TNB列表
        DataManager.getInstance().cleanUnfinishedEventTnbMap();
        // 清除新任务TNB列表
        DataManager.getInstance().cleanNewTnbMap();
        // 清除权限
        JavaBeanManager.getInstance().getAuthority().getAuthres().clear();
        // 清除航班变更信息
        DataManager.getInstance().getFlightChangeMsgList().clear();
        JavaBeanManager.getInstance().getFlightchangeList().clear();

        // 清除FLG10
        JavaBeanManager.getInstance().deleteFLG10TaskListLinshiData();
        // 清除清洁监控列表标记位
        JavaBeanManager.getInstance().setSelectPos(0);
        // 清除任务监控过滤项
        JavaBeanManager.getInstance().deleteQJMonitorState();
        //删除已转发任务列表
        JavaBeanManager.getInstance().deleteTaskForwardList();
        //清除行李条码初始化标识
        JavaBeanManager.getInstance().setInitQueryLuggage(false);
        //清除清洁群组信息
        JavaBeanManager.getInstance().setWorkGroupLoadInfo(null);
        // 清除任务执行模板
        // TaskExcuteView.destoryInstance();
        // 清空上报服务标注列表
        ServiceLabelUtil.clearReportServiceLabel();
        // 清除单据信息
        DataManager.getInstance().cleanDocMap();
        // 清除密码
        DataBaseManager.getInstance().insertShared(ParameterModel.T_LAST_USER, ParameterModel.LOGIN_PASSWORD, "");
        EffectManager.getInstance().ttsCancel();
        // 恢复TTS状态
        EffectManager.getInstance().ttsResume();

        // 返回主界面
        // Body.getInstance().reset();

        // 重置消息盒子
        DataManager.getInstance().getTaskChangeList().clear();
        DataManager.getInstance().getFlightChangeList().clear();
        DataManager.getInstance().getMessageList().clear();
        DataManager.getInstance().setUnCheckNumber(0);

        // TODO 注销刷新UI，回到主页面
        ActionManager.getInstance().updateUI(MessageModel.RKOE);
        ActionManager.getInstance().getSecurityResponseAction().updateAccountStateProvider(null);
        sendBraodcast(new Intent(SecurityResponseImpl.ACTION_LOGOUT));
        ActionManager.getInstance().getSecurityResponseAction().sendPttLogoutBraodcast();
        System.gc();
    }


    /**
     * 发送广播消息
     *
     * @param intent
     */
    private void sendBraodcast(Intent intent) {
        Context context = DataBaseManager.getInstance().getContext();
        if (context != null) {
            //设置被停止的应用也能接收到广播
            intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
            context.sendBroadcast(intent);
        } else {
            Log.w("C_sys", "sendBraodcast: context is null" + "login state:" + ServiceManage.getInstance().getIsLogon());
        }
    }

    /**
     * 登录成功后派发普通IQRY信息
     *
     */
    public void setLogon(boolean logon) {

        _isLogon = logon;
        //设置发送信息状态
        ServiceManage.getInstance().setSendMsgFlag(logon);
    }

    /**
     * 获取是否已经登录
     *
     * @return
     */
    public boolean getIsLogon() {
        return _isLogon;
    }

    /**
     * 二：添加服务到列表
     *
     * @param services socket网络服务
     */
    public void addService(BaseService... services) {
        if (services != null) {
            for (BaseService service : services) {
                serviceArray.add(service);
            }
        }
    }

    /**
     * 停止GPS服务
     **/
    public void stopGPSService() {
        ThreadManager.getInstance().stopGPSThread();
        if (gpsService != null) {
            gpsService.removeGPSListener();
            gpsService = null;
        }
    }

    public void sendMessage(String message, int delay, ProgressBar p) {
        sendMessage(message, delay, p, null);
    }

    /**
     * 发送信息到网关
     *
     * @param message
     * @param delay   延时时间
     * @throws IOException
     * @throws IOException
     */
    public void sendMessage(String message, int delay, ProgressBar p, MessageSendSuccessListener successListener) {

        if (S.isEmpty(message)) {
            return;
        }
        if (sendMsgFlag) {
            // 创建Message对象
            SendMsgThread sendMsgThread = ThreadManager.getInstance().getSendMsgThread();
            SendMsgBean msgBean = new SendMsgBean(message, delay, p, successListener);
            sendMsgThread.sendMsg(msgBean);
        }
    }

    public void sendMessage(final String message, final int delay, final boolean needcheckAllNet, final ProgressBar p) {
        sendMessage(message, delay, needcheckAllNet, p, null);
    }

    /**
     * 发送信息到网关
     *
     * @param message
     * @param delay   延时时间 @
     * @throws IOException
     * @throws IOException
     */
    public void sendMessage(final String message, final int delay, final boolean needcheckAllNet, final ProgressBar p,
                            final MessageSendSuccessListener sendSuccessListener) {
        final BaseService service = getUsingPushService();
        if (S.isEmpty(message))
            return;
        if (service != null && service.isConnected()) {
            Log.i("tag", "2");
            try {
                if (p != null) {
                    service.getMyHandler().post(new Runnable() {

                        @Override
                        public void run() {
                            p.setVisibility(View.VISIBLE);
                        }
                    });
                    String ms = MyMessage.getMS(message);
                    waitProcess.clear();
                    String mt = MyMessage.getMT(message);
                    ProgressBean progressBean = new ProgressBean(mt, p, sendSuccessListener);
                    waitProcess.put(ms, progressBean);
                    handler.postDelayed(waitRecvice, 12 * 1000);// 12秒后，关闭等待对话框
                }
                if (S.isNotEmpty(service.getLocalIpAddress())) {
                    service.sendMessage(message);
                }
                // 否则关闭网络
                else {
                    service.close();
                    sendNetStatusMsg(NetUtils.GETADDRESS_SUCCESS, service);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
//				WriteLog.getInstance().writeLog(context.getString(R.string.sendError) + e.getMessage());
                int f = message.indexOf(",");
                System.out.println("############socket is disconnect################22");
                service.close();
                sendNetStatusMsg(NetUtils.GETADDRESS_SUCCESS, service);
                if (!MessageModel.SGOC.equals(message.substring(f, f + 4))) {
					sendMsgError(service, context.getString(R.string.serviceError), message, delay, needcheckAllNet, p);
                }
            } catch (SocketException e) {
                e.printStackTrace();
//				WriteLog.getInstance().writeLog(context.getString(R.string.sendError) + e.getMessage());
                System.out.println("############socket is disconnect################33");
                service.close();
                sendNetStatusMsg(NetUtils.GETADDRESS_SUCCESS, service);
                e.printStackTrace();
                Log.e("ServiceManager", e.getMessage());
                int f = message.indexOf(",");
                String sendMsg = message.substring(f + 1, f + 5);
                System.out.println("错误消息" + sendMsg);
                if (!MessageModel.SGOC.equals(sendMsg) && !MessageModel.IQRY.equals(sendMsg)) {
					sendMsgError(service, context.getString(R.string.sendError2), message, delay, needcheckAllNet, p);
                }
            } catch (IOException e) {
                e.printStackTrace();
//				WriteLog.getInstance().writeLog(context.getString(R.string.sendError) + e.getMessage());
                System.out.println("############socket is disconnect################44");
                service.close();
                sendNetStatusMsg(NetUtils.GETADDRESS_SUCCESS, service);
                Log.e("ServiceManager", e.getMessage());
                e.printStackTrace();
                int f = message.indexOf(",");
                String sendMsg = message.substring(f + 1, f + 5);
                System.out.println("错误消息" + sendMsg);
                if (!MessageModel.SGOC.equals(sendMsg) && !MessageModel.IQRY.equals(sendMsg)) {
					sendMsgError(service, context.getString(R.string.sendError2), message, delay, needcheckAllNet, p);
                }
            }
        } else {
            if (needcheckAllNet) {
                ThreadManager.getInstance().stopHeartThread();// 关闭心跳
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        clearWaitDialog(null);
						//EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, context.getString(R.string.offLine), false);
                    }
                });
            }
        }
    }

    private void sendMsgError(final BaseService service, final String tip, String msg, int delay, boolean b,
                              ProgressBar p) {
//        WriteLog.getInstance().writeLog(tip);
        if (isLastService(service)) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    clearWaitDialog(null);
                    ShowToast.get().show(tip);
                }
            });
        } else {
            sendMessage(msg, delay, b, p);
        }
    }

    /**
     * 发送信息到网关
     *
     * @param message
     * @throws IOException
     * @ @throws
     * IOException
     */
    public void sendMessage(String message) {
        sendMessage(message, 0, null);
    }

    public void sendMessage(String message, ProgressBar p, MessageSendSuccessListener sendSuccessListener) {
        sendMessage(message, 0, p, sendSuccessListener);
    }

    /**
     * 发送信息到所有可用网关
     *
     * @throws IOException
     * @ @throws
     * IOException
     */
    public void sendMessageAllGW(int tab) {

        for (BaseService service : serviceArray) {

            // 如果该网络是连接状态,且网络不是关闭状态
            if (service != null && service.isConnected()) {
                // 发送消息
                try {
                    service.sendTestSGOCMessage(tab);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 发送信息到网关
     *
     * @param message
     * @throws IOException
     * @ @throws
     * IOException
     */
    public void sendMessage(String message, boolean needcheckAllNet) {
        sendMessage(message, 0, null);
    }

    public void sendMessage(String message, boolean needcheckAllNet, ProgressBar p) {
        sendMessage(message, 0, p);
    }

    /**
     * 停止所有服务
     **/
    public void stopAllService() {
        ThreadManager.getInstance().stopAllThread();
        for (BaseService service : serviceArray) {
            // service.close();
            if (service != null) {
                service = null;
            }
        }
        serviceArray.clear();
    }

    // /**
    // * 停止指定服务（某网断开时）
    // *
    // * @param _service
    // */
    // public void stopService(BaseService _service) {
    // for (BaseService service : serviceArray) {
    // if (_service.equals(service)) {
    // service.isSucess = true;
    // service.close();
    // service.removeThread();
    // serviceArray.remove(_service);
    // service = null;
    // }
    // }
    // }

    /**
     * 启动所有服务
     **/
    public void startAllService() {
        for (BaseService service : serviceArray) {
            service.checkAvailable();
        }
    }

    // /**
    // * 网络断开时自动重连
    // * @param _service
    // */
    // public void startNetService(BaseService _service) {
    // if (_service != null)
    // addService(_service);
    //
    // startService(_service);
    //
    // ThreadManager.getInstance().startHeartThread();// 启动心跳线程
    // }
    //
    // /**
    // * 启动指定服务（某网断开时）
    // *
    // * @param _service
    // */
    // private void startService(BaseService _service) {
    // _service.start();
    // }

    /**
     * 启动Gps服务
     **/
    public void startGpsService() {
        if (gpsService == null) {
            gpsService = new GpsService(DataBaseManager.getInstance().getContext());
        }
    }

    /**
     * 获取推送服务器正在使用的socket服务
     *
     * @return
     */
    public BaseService getUsingPushService() {
        BaseService resultservice = null;
        for (BaseService service : serviceArray) {
            if (service.isConnected()) {
                resultservice = service;
                break;
            }
        }
        return resultservice;
    }

    /**
     * 获取当前正在使用的socket服务
     *
     * @return
     */
    public BaseService getUsingRestfulService() {
        BaseService resultservice = null;
        for (BaseService service : serviceArray) {
            // 如果有IP地址
            if (service.hasLocalAddress()) {
                resultservice = service;
                break;
            }
        }
        return resultservice;
    }

    public BaseService getNextUsingService() {
        BaseService resultservice = null;

        if (serviceArray.size() > 0) {
            if (currentNetIndex < serviceArray.size() - 1) {
                currentNetIndex++;
            } else {
                currentNetIndex = 0;
            }

            if (serviceArray.get(currentNetIndex).isConnected()) {
                resultservice = serviceArray.get(currentNetIndex);
            } else {
                if (currentNetIndex < serviceArray.size() - 1) {
                    currentNetIndex++;
                } else {
                    currentNetIndex = 0;
                }
                if (serviceArray.get(currentNetIndex).isConnected()) {
                    resultservice = serviceArray.get(currentNetIndex);
                } else {
                    if (currentNetIndex < serviceArray.size() - 1) {
                        currentNetIndex++;
                    } else {
                        currentNetIndex = 0;
                    }
                    if (serviceArray.get(currentNetIndex).isConnected()) {
                        resultservice = serviceArray.get(currentNetIndex);
                    }
                }
            }
        }

        return resultservice;
    }

    /**
     * 获取当前网路的使用顺序索引
     **/
    public boolean isLastService(BaseService service) {
        if (service != null && serviceArray.indexOf(service) == serviceArray.size() - 1)
            return true;
        return false;
    }

    /**
     * 获取wifi信息包
     *
     * @return
     */
    public WifiInfo getWifiInfo() {
        WifiInfo wifiinfo = null;
        for (BaseService service : serviceArray) {
            if (service.getClass().equals(WifiNetService.class)) {
                wifiinfo = ((WifiNetService) service).GetWifiInfo();
                break;
            }
        }
        return wifiinfo;
    }

    /**
     * 清除等待对话框
     **/
    public void clearWaitDialog(String rms) {
        if (rms == null) {
            Set<String> set = waitProcess.keySet();
            for (String s : set) {
                ProgressBean progressBean = waitProcess.get(s);
                {
                    ProgressBar progress = progressBean.getProgress();
                    if (progress != null) {
                        progress.setVisibility(View.INVISIBLE);
                    }
                }
            }
            waitProcess.clear();
            handler.removeCallbacks(waitRecvice);
        } else {
            ProgressBean progressBean = waitProcess.get(rms);
            if (progressBean != null) {
                ProgressBar progress = progressBean.getProgress();
                if (progress != null) {
                    progress.setVisibility(View.INVISIBLE);
                    waitProcess.clear();
                    handler.removeCallbacks(waitRecvice);
                }
                if (progressBean.getSuccessListener() != null) {
                    Log.d("C_process", "process success:" + rms);
                    progressBean.getSuccessListener().onSuccess();
                }
            }
        }
    }

    /**
     * 获取当前gps服务
     *
     * @return
     */
    public GpsService getGpsService() {
        return gpsService;
    }

    /**
     * 刷新网络状态
     */
    public void updateUsingNetStatus(int _nNetType, String _sNetIp) {

        WriteLog.getInstance().writeDebugLog(context.getString(R.string.DEBUG_BROAD_NET_TYPE)+_nNetType);
        WriteLog.getInstance().writeDebugLog(context.getString(R.string.DEBUG_BROAD_NET_IP)+_sNetIp);
        // 10 --公网关闭
        // 11 --公网开启
        // 20 --专网关闭
        // 21 --专网开启
        // 30 --WIFI关闭
        // 31 --WIFI开启
        String sNetTypeClass = null;
        switch (_nNetType) {
            case 10:
            case 11:
                sNetIp = _sNetIp;
                sNetTypeClass = "PublicNetService";
                break;
            case 20:
            case 21:
                sNetIp = _sNetIp;
                sNetTypeClass = "PrivateNetService";
                break;
            case 30:
            case 31:
                sNetIp = _sNetIp;
                sNetTypeClass = "WifiNetService";
                break;

            default:
                break;
        }

        BaseService serviceNet = null;
        String sNetStatus = null;
        for (BaseService service : serviceArray) {
            // String sName = service.getClass().getSimpleName();
            if (service.getClass().getSimpleName().equals(sNetTypeClass)) {
                serviceNet = service;
                serviceNet.setLocalAddress(sNetIp);
                break;
            }
        }

        if (serviceNet != null) {
            if (_nNetType % 10 == 0) {
                sNetStatus = NetUtils.GETADDRESS_FAILED;
                sendNetStatusMsg(sNetStatus, serviceNet);
                serviceNet.close();// 关闭socketChannel
            } else if (!serviceNet.isConnected()) {
                sNetStatus = NetUtils.GETADDRESS_SUCCESS;
                sendNetStatusMsg(sNetStatus, serviceNet);
            }
        }

        BaseService resfulService = ServiceManage.getInstance().getUsingRestfulService();
        if (resfulService != null) {
            // TODO 保存Restful的IP地址
            String restfulIp = resfulService.getRestfulIP();
            int restfulPort= resfulService.getRestfulPort();
            RestfulUri.webIPAddress = restfulIp;
            RestfulUri.webPort = restfulPort;
        }
    }

    private void sendNetStatusMsg(String _sNetStatus, BaseService _bService) {
        // Header.getInstance().sendHeaderBroadcast(NetUtils.SENDNETSTATUS,
        // _sNetStatus, _bService);
    }
}
